/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.upload;

import cn.com.taiji.sdk.model.comm.protocol.transaction.RechargeUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.transaction.RechargeUploadResponse;
import cn.com.taiji.sdk.model.comm.protocol.user.*;
import com.wttech.dzzf.process.dao.RechargeInfoDao;
import com.wttech.dzzf.process.service.user.UserDetailInfosCreatorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import static cn.com.taiji.sdk.comm.ETCCommHelper.upload;
import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;
import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROVINCE_CODE;

/**
 * 充值信息上传
 *
 * @author MaShibo
 * @date 2017/11/13.
 */
@Service
public class RechargeInfosUploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RechargeInfosUploadService.class);

    @Resource
    private RechargeInfoDao rechargeInfoDao;

    @Resource
    private ThreadPoolTaskExecutor executor;

    @Resource
    private UserDetailInfosCreatorService userDetailInfosCreatorService;

    private void process() {
        int total = rechargeInfoDao.queryTestRechargeNum();
        LOGGER.info("共{}条充值数据待处理", total);
        int count = (int) Math.ceil((double) total / DEFAULT_PROCESS_NUM);
        LOGGER.info("每次处理{}条，共需处理{}次", DEFAULT_PROCESS_NUM, count);
        for (int i = 0; i < count; i++) {
            int num = i + 1;
            LOGGER.info("第{}次开始处理", num);
            int startRow = (num - 1) * DEFAULT_PROCESS_NUM + 1;
            int endRow = num * DEFAULT_PROCESS_NUM;
            List<Future<Void>> futures = new ArrayList<>(DEFAULT_PROCESS_NUM);
            List<RechargeUploadRequest> rechargs = rechargeInfoDao.queryRechargeUploadInfos(startRow, endRow);
            rechargs.forEach(recharge -> futures.add(executor.submit(new SubProcessThread(recharge))));
            userDetailInfosCreatorService.getFutureResult(futures);
            LOGGER.info("第{}次结束处理", num);
        }
        LOGGER.info("处理完毕");
        executor.shutdown();
    }

    void processSingleRecharge(RechargeUploadRequest recharge) {
        try {
            String cardId = recharge.getCardId();
            processUserAboutInfo(cardId);
            RechargeUploadResponse rechargeRsp = upload(recharge.getFileName(DEFAULT_PROVINCE_CODE), recharge, RechargeUploadResponse.class);
            LOGGER.info("充值信息上传响应{}", rechargeRsp.getInfo());
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
        }
    }

    void processUserAboutInfo(String cardId) throws IOException {
        CardUploadRequest card = rechargeInfoDao.queryCardUploadInfo(cardId);
        if (card != null) {
            String userId = card.getUserId();
            UserUploadRequest user = rechargeInfoDao.queryUserUploadInfo(userId);
            String vehicleId = card.getVehicleId();
            VehicleUploadRequest vehicle = rechargeInfoDao.queryVehicleUploadInfo(vehicleId);

            if (user != null) {
                UserUploadResponse userRsp;
                try {
                    userRsp = upload(user.getFileName(DEFAULT_PROVINCE_CODE), user, UserUploadResponse.class);
                    LOGGER.info("客户信息上传响应{}", userRsp.getInfo());
                } catch (Exception e){
                    user.setOperation(2);
                    userRsp = upload(user.getFileName(DEFAULT_PROVINCE_CODE), user, UserUploadResponse.class);
                    LOGGER.info("客户信息上传响应{}", userRsp.getInfo());
                }

            }
            if (vehicle != null) {
                VehicleUploadResponse vehicleRsp;
                try {
                    vehicleRsp = upload(vehicle.getFileName(DEFAULT_PROVINCE_CODE), vehicle, VehicleUploadResponse.class);
                    LOGGER.info("车辆信息上传响应{}", vehicleRsp.getInfo());
                } catch (Exception e){
                    vehicle.setOperation(2);
                    vehicleRsp = upload(vehicle.getFileName(DEFAULT_PROVINCE_CODE), vehicle, VehicleUploadResponse.class);
                    LOGGER.info("车辆信息上传响应{}", vehicleRsp.getInfo());
                }

            }

            CardUploadResponse cardRsp;
            try {
                cardRsp = upload(card.getFileName(DEFAULT_PROVINCE_CODE), card, CardUploadResponse.class);
                LOGGER.info("卡片信息上传响应{}", cardRsp.getInfo());
            } catch (Exception e){
                card.setOperation(2);
                cardRsp = upload(card.getFileName(DEFAULT_PROVINCE_CODE), card, CardUploadResponse.class);
                LOGGER.info("卡片信息上传响应{}", cardRsp.getInfo());
            }
        }
    }

    private class SubProcessThread implements Callable<Void> {

        private RechargeUploadRequest recharge;

        public SubProcessThread(RechargeUploadRequest recharge) {
            this.recharge = recharge;
        }

        @Override
        public Void call() throws Exception {
            processSingleRecharge(recharge);
            return null;
        }
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        RechargeInfosUploadService service = context.getBean(RechargeInfosUploadService.class);
        service.process();
    }

}
